<?php

error_reporting(-1);
ini_set('display_errors', 1);

require APPPATH . 'core/feed/feed_bank.php';

class adv extends CI_Controller {

    protected $data;
    protected $submitdata;

    function __construct() {
        $this->_initdata();
    }

    function index() {
        $this->data['page_title'] = "Rao Vặt";
        $this->data['page_css'] = "rao-vat";
        $this->data['keyword'] = "Nhập nội dung cần tìm";
        $this->data['page_name'] = "adv";

        $this->data['aAdv_Box1'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_VCHH, 0, 5); //ADV_CATE_1: Vận chuyển hàng hóa
        $this->data['ADV_CATE_1'] = ADV_CATE_VCHH; //for "Xem thêm"

        $this->data['aAdv_Box2'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_TTHQ, 0, 5); //ADV_CATE_2: Thủ tục hải quan
        $this->data['ADV_CATE_2'] = ADV_CATE_TTHQ; //for "Xem thêm"

        $this->data['aAdv_Box3'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_KB, 0, 5); //ADV_CATE_3: Kho bãi
        $this->data['ADV_CATE_3'] = ADV_CATE_KB; //for "Xem thêm"

        $this->data['aAdv_Box4'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_DGBB, 0, 5); //ADV_CATE_1: Đóng gói bao bì
        $this->data['ADV_CATE_4'] = ADV_CATE_DGBB; //for "Xem thêm"

        $this->data['aAdv_Box5'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_BHHH, 0, 5); //ADV_CATE_2: Bảo hiểm hàng hóa
        $this->data['ADV_CATE_5'] = ADV_CATE_BHHH; //for "Xem thêm"

        $this->data['aAdv_Box6'] = $this->Fe_adv_model->_get_adv_list_bycate(ADV_CATE_LK, 0, 5); //ADV_CATE_3: Loại khác
        $this->data['ADV_CATE_6'] = ADV_CATE_LK; //for "Xem thêm"

        $this->show($this->data);
    }

    //Controller: search
    function search() {
        $isSearch = "";
        $keyWord = "";
        $advCate = "";
        $city = "";
        $search_criteria = "";
        $page = "";

        //get param
        //1. from submit form
        //2. from URL param.
        if (!empty($_POST['isPost']) || ($this->uri->segment(3) != "")) { //from URL
            $isSearch = 1;
            if ($this->uri->segment(3) != "") {
                //get current page + search criteria.
                $str = $this->uri->segment(3);
                $a = explode("-", $str);
                $page = $a[count($a) - 1];
                $search_criteria = $a[0];
                //get detail search criteria
                $a = explode("&", $search_criteria);
                if (count($a) > 0) {
                    $keyWord = rawurldecode($this->_get_value_explode($a[0], "="));
                    $advCate = rawurldecode($this->_get_value_explode($a[1], "="));
                    $city = rawurldecode($this->_get_value_explode($a[2], "="));
                }
            } else { //from submit form.
                $keyWord = $_POST['txt_Adv_Keyword'];
                $advCate = $_POST['cbo_ADV_Cate'];
                $city = $_POST['cbo_ADV_City'];
                $this->data['cateName'] = $_POST['cateName'];
            }
        }
        if ($isSearch) {
            $iCurPage = 1;
            $iCurPage = $page;
            $iRow_Count = 0;
            @$limit = PAGESIZE;
            $start = $iCurPage * PAGESIZE - PAGESIZE;
            if (!($start > 0)) {
                $start = 0;
            }
            $eu = ($start - 0);
            if (!$limit > 0) {
                $limit = 20;
            }

            if (strpos($keyWord, '--') === false && strpos($keyWord, '/') === false && strpos($keyWord, '*') === false && strpos($keyWord, '1=1') === false) {
                list($iRow_Count, $this->data['aAdv']) = $this->Fe_adv_model->_search_adv_list($keyWord, $advCate, $city, $eu, $limit);
            } else {

                list($iRow_Count, $this->data['aAdv']) = "";
            }
            //create criteria for paging search:
            $search_criteria = "k=" . rawurlencode($keyWord) . "&cate_id=" . $advCate . "&city_id=" . $city; //application/config/config.php --> chỉnh "permitted_uri_chars" thêm \+
            $this->data['paging'] = $this->_paging_search($search_criteria, $iCurPage, ceil($iRow_Count / PAGESIZE), $this->config->item('base_url') . "rao-vat/tim-kiem", $iRow_Count);
            $this->data['cur_page'] = 'search';
            $this->data['txt_Adv_Keyword'] = $keyWord;
            $this->data['adv_cate_id'] = $advCate;
            $this->data['city_id'] = $city;

            //data for layout.
            $this->data['page_title'] = "Rao Vặt";
            $this->data['page_css'] = "rao-vat-search";
            $this->data['keyword'] = "Nhập nội dung cần tìm";
            $this->data['page_name'] = "adv_search";

            $this->data['search'] = 1;
            $this->data['previous_id'] = 1;
            $this->data['page_title'] = "Rao Vặt";
            $this->data['msg'] = "";
            $this->show($this->data);
        }
    }

    function _get_value_explode($str, $delimiter) {
        $a = explode($delimiter, $str);
        if (count($a) > 0)
            return $a[count($a) - 1];
        else
            return "";
    }

    //Controller: xem tin chi tiet
    function adv_details() {
        $this->data['page_css'] = "rao-vat-detail";
        $this->data['page_name'] = "adv_details";


        //get news_id from URL
        $str = $this->uri->segment($this->uri->total_segments());
        $a = explode(".", $str);
        $a = explode("-", $a[0]);
        $adv_id = $a[count($a) - 1];
        $this->data['aAdvDetails'] = $this->Fe_adv_model->get_adv_detail_by_id($adv_id);

        $this->data['aAdv_Others'] = $this->Fe_adv_model->_get_adv_list($this->data['aAdvDetails'][0]->adv_id, 0, 5);

        $this->data['page_title'] = "Rao Vặt - " . $this->data['aAdvDetails'][0]->title;

        //cho nay k bik de lam gi nen tam thoi comment
        //$page_paging = $this->config->item('base_url') . "hoi-dap/page";
        //$this->show_adv_list($page_paging);
        $this->show($this->data);
    }

    //Controller: add
    function add() {
        $this->data['page_title'] = "Rao Vặt - Đăng tin";
        $this->data['page_css'] = "rao-vat-dangtin";
        $this->data['keyword'] = "Nhập nội dung cần tìm";
        $this->data['page_name'] = "adv_add";

        if (!empty($_POST['isPost']) && ($_POST['isPost'] == 1)) {
            if ($_SESSION['captchar'] != $_POST['txt_capchar']) {
                $this->data['title'] = $_POST['txt_title'];
                $this->data['desc'] = $_POST['txt_desc'];
                $this->data['adv_cate_id'] = $_POST['cbo_ADV_Cate'];
                $this->data['city_id'] = $_POST['cbo_ADV_City'];
                $this->data['user_full_name'] = $_POST['txt_user_full_name'];
                $this->data['user_tel'] = $_POST['txt_user_tel'];
                //get submit data
                $this->data['msg'] = "Mã xác nhận không đúng.";
            } else {
                $this->submitdata['title'] = $_POST['txt_title'];
                $this->submitdata['url'] = convertToVn(trim($_POST['txt_title']));
                $this->submitdata['desc'] = htmlspecialchars(nl2br($_POST['txt_desc']));
                $this->submitdata['adv_cate_id'] = $_POST['cbo_ADV_Cate'];
                $this->submitdata['city_id'] = $_POST['cbo_ADV_City'];
                $this->submitdata['user_full_name'] = $_POST['txt_user_full_name'];
                $this->submitdata['user_tel'] = $_POST['txt_user_tel'];
                $this->submitdata['user_ip'] = $_SERVER['REMOTE_ADDR'];
                $this->submitdata['create_date'] = date("Y-m-d H:i:s");
                $this->submitdata['status'] = "0";

                
                if (isset($_POST['hidImgList']) && strlen($_POST['hidImgList']) > 0) {
                    $arr_img = explode(";", $_POST['hidImgList']);
                    $img_list = '';
                    foreach ($arr_img as $img) {
                        if ($img_list != '') {
                            $img_list.=';';
                        }
                        $img_list .= $this->build_img_name($img);
                    }
                    $this->submitdata['img'] = $img_list;
                }


                //insert newscate
                $insert_id = $this->Fe_adv_model->_insert_adv('adv2013', $this->submitdata);
                //thong bao & redirect page
                $_SESSION['msg'] = "EximGate.vn đã nhận được tin Rao vặt của bạn. Hệ thống sẽ kiểm duyệt và sắp xếp đăng tin của bạn trong thời gian sớm nhất. Xin cảm ơn.";
                $this->load->helper('url');
                echo "<script>window.location='" . $this->data['base_url'] . 'rao-vat/dang-tin' . "'</script>";
            }
        }
        $this->create_captchar(120, 32);
        $this->load->view('common/common_view', $this->data);
    }

    function create_captchar($width, $height) {
        $word = $this->generateCode(4);
        $_SESSION['captchar'] = $word;

        //CI settings
        $vals = array(
            'word' => $word,
            'img_path' => './style/captcha/',
            'img_url' => '/style/captcha/',
            'font_path' => './system/fonts/monofont.ttf',
            'img_width' => $width,
            'img_height' => $height,
            'expiration' => 7200
        );
        $cap = create_captcha($vals);

        //print output
        $this->data['captchar_img'] = $cap['image'];
    }

    function generateCode($characters) {
        $possible = '23456789bcdfghjkmnpqrstvwxyz';
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible) - 1), 1);
            $i++;
        }
        return $code;
    }

    function show_adv_list($page_paging) {
        $iCurPage = 1;
        $iCurPage = $this->uri->segment(2);
        $iRow_Count = 0;
        @$limit = PAGESIZE;
        $start = $iCurPage * PAGESIZE - PAGESIZE;
        if (!($start > 0)) {
            $start = 0;
        }
        $eu = ($start - 0);
        if (!$limit > 0) {
            $limit = 20;
        }
        list($iRow_Count, $this->data['aFAQ']) = $this->Frontendmodel->_get_faq_paging("*", " faq.status='1' ", " order by faq_id desc ", $eu, $limit);
        $this->data['paging'] = $this->paging($iCurPage, ceil($iRow_Count / PAGESIZE), $page_paging, $iRow_Count);
        $this->data['cur_page'] = $iCurPage;
        $this->data['previous_id'] = 1;
    }

    //Phân trang news
    function paging($page, $totalpage, $pagelink, $totalrows) {
        if ($page == "")
            $page = 1;

        $this->data['cur_page'] = $page;

        $paging_str = '';
        if ($page > 1)
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next" onclick="location.href=' . "'" . $pagelink . '/' . ($page - 1) . "'" . '"><img src="' . $this->config->item('base_url') . 'style/images/img20.gif" border="0"></a>';
        else
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next"><img src="' . $this->config->item('base_url') . 'style/images/img20.gif" border="0"></a>';

        // list 10 pagelink
        $startpage = 1;
        if ($page > 5)
            $startpage = $page - 4;
        $endpage = $totalpage;
        if ($totalpage - $page > 5)
            $endpage = $page + 5;
        for ($i = $startpage; $i < $page; $i++)
            $paging_str .= '<a href="' . $pagelink . '/' . $i . '" class="paging-item">' . $i . '</a>';

        $paging_str .= '<a href="' . $pagelink . '/' . $i . '" class="paging-item-selected">' . $page . '</a>';

        for ($i = $page + 1; $i <= $endpage; $i++)
            $paging_str .= '<a href="' . $pagelink . '/' . $i . '" class="paging-item">' . $i . '</a>';

        if ($page < $totalpage)
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next" onclick="location.href=' . "'" . $pagelink . '/' . ($page + 1) . "'" . '"><img src="' . $this->config->item('base_url') . 'style/images/img21.gif" border="0"></a>';
        //$paging_str .= '<img src="'.$this->config->item('base_url').'style/img/img22_arrow_right.gif" align="absmiddle" style="cursor:pointer;" onclick="location.href=' ."'".$pagelink.'/'.($page+1).".html'". '">';
        else
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next"><img src="' . $this->config->item('base_url') . 'style/images/img21.gif" border="0"></a>';
        $paging_str .= '&nbsp;&nbsp;&nbsp;</span></td>';

        //$paging_str .= '&nbsp;&nbsp;&nbsp;<span class="paging_total"><strong>[ </strong>T&#7893;ng c&#7897;ng: <font color="Red">' .$totalrows. '</font> k&#7871;t qu&#7843; <strong> ]</strong></span>';
        return $paging_str;
    }

    //Phân trang Rao Vat :
    //* $search_criteria : các tiêu chí search.
    //* $page : trang hiện hành
    //* $totalpage : tổng trang
    //* $pagelink : URL tạo link full dùng để bấm trên list page.
    //* $totalrows : tổng số record tìm thấy.
    function _paging_search($search_criteria, $page, $totalpage, $pagelink, $totalrows) {
        if ($page == "")
            $page = 1;

        $paging_str = '';
        if ($page > 1)
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next" onclick="location.href=' . "'" . $pagelink . '/' . $search_criteria . "-" . ($page - 1) . "'" . '"><img src="' . $this->config->item('base_url') . 'style/images/img20.gif" border="0"></a>';
        else
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next"><img src="' . $this->config->item('base_url') . 'style/images/img20.gif" border="0"></a>';

        // list 10 pagelink
        $startpage = 1;
        if ($page > 5)
            $startpage = $page - 4;
        $endpage = $totalpage;
        if ($totalpage - $page > 5)
            $endpage = $page + 5;
        for ($i = $startpage; $i < $page; $i++)
            $paging_str .= '<a href="' . $pagelink . '/' . $search_criteria . "-" . $i . '" class="paging-item">' . $i . '</a>';

        $paging_str .= '<a href="' . $pagelink . '/' . $search_criteria . "-" . $i . '" class="paging-item-selected">' . $page . '</a>';

        for ($i = $page + 1; $i <= $endpage; $i++)
            $paging_str .= '<a href="' . $pagelink . '/' . $search_criteria . "-" . $i . '" class="paging-item">' . $i . '</a>';

        if ($page < $totalpage)
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next" onclick="location.href=' . "'" . $pagelink . '/' . $search_criteria . "-" . ($page + 1) . "'" . '"><img src="' . $this->config->item('base_url') . 'style/images/img21.gif" border="0"></a>';
        else
            $paging_str .= '<a href="javascript:void(0);" class="paging-previous_next"><img src="' . $this->config->item('base_url') . 'style/images/img21.gif" border="0"></a>';

        $paging_str .= '&nbsp;&nbsp;&nbsp;</span></td>';
        return $paging_str;
    }

    function _check_page_views($id) {
        if ($this->Frontendmodel->_check_views("PAGEVIEWS") == false) {
            $page_views = $this->Frontendmodel->_update_config($id);
            $this->Frontendmodel->_set_session("PAGEVIEWS", $page_views);
        }
    }

    function _initdata() {
        parent::__construct();
        session_start();
        $this->load->helper('captcha');
        $this->load->helper('eximcached');
        
        $this->load->model('Frontendmodel');
        $this->load->model('Fe_adv_model');
        $this->load->model('Fe_company_model');
        $this->load->model('Fe_docs_model');
        $this->load->model('Fe_forwarding_model');
        $this->load->model('Fe_knowledge_model');
        $this->load->model('Fe_faq_model');
        
        //load submenu and footer
        list($this->data['aLatestNews']) = get_latest_news($this->Frontendmodel, 7);
        list($this->data['aCate2']) = get_newscate_list(NEWS_CATE_VBPQ, $this->Frontendmodel);
        $this->data['aCate3'] = $this->Fe_knowledge_model->get_all_cate();
        $this->data['aCate4'] = _get_all_cate_customs($this->Frontendmodel);
        $this->data['aCate5'] = $this->Fe_forwarding_model->get_all_cate();
        $this->data['aCate6'] = $this->Fe_faq_model->_get_faq_cate_list();

        //check message
        if (isset($_SESSION['msg'])) {
            $this->data['msg'] = $_SESSION['msg'];
            $_SESSION['msg'] = "";
        }
        $this->data['page_header'] = "header";
        $this->data['page_name'] = "adv";
        $this->data['keyword'] = "Nhập nội dung cần tìm";
        $this->data['page_rightbar'] = "rightbar";
        $this->data['page_footer'] = "footer";
        $this->data['base_url'] = $this->config->item('base_url');
        $this->data['img_url'] = $this->config->item('img_url');
        $this->data['current_url'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $this->data['aCityList'] = get_cities_list($this->Frontendmodel);
        $feed = new feed_bank();
        $this->data['gold'] = get_feed_gold($feed);
        $this->data['exchange_rate'] = get_feed_exchange($feed);

        //get Adv Cate (box search) --> for Rao Vat
        $this->data['aAdvCate'] = $this->Fe_adv_model->_get_adv_cate_list();

        //get City list (box search) --> for Rao Vat
        $this->data['aCity'] = $this->Fe_adv_model->_get_city_list();

    }

    function upload() {
        // A list of permitted file extensions
        $allowed = array('png', 'jpg', 'gif');
        if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) {

            $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
            if (!in_array(strtolower($extension), $allowed)) {
                echo '{"status":"error"}';
                exit;
            }
            $file_name = $this->build_img_name($_FILES['upl']['name']);

            $folder = IMAGE_ROOT . IMAGE_DIR . 'uploads/';
            $destImg = $folder . $file_name;

            if (move_uploaded_file($_FILES['upl']['tmp_name'], $destImg)) {
                exit;
            }
        }
    }

    function build_img_name($img) {
        $session = substr(session_id(), 3, 5);
        $ymd = date('ymd');
        return $ymd . $session . $img;
    }

}

?>